/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2020年03月19日
*   版    本：v1.0.0
*   描    述：
*   Copyright (C) 2020 All rights reserved.
*   
* ================================================================*/


#include <iostream>
#include <vector>
using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */


class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        int preindex = 0;
        int prestart = 0, preend = pre.size()-1;
        int poststart = 0, postend = post.size()-1;
        if(pre.size() == 0){
            return NULL;
        }

        return constructBinaryTree(pre, post, prestart, preend, poststart, postend);
    }

    TreeNode* constructBinaryTree(vector<int>& pre, vector<int>& post, int prestart, int preend, int poststart, int postend){
        if(poststart > postend || prestart > preend){
            return NULL;
        }

        TreeNode* root = new TreeNode(pre[prestart]);
        if(prestart == preend){
            return root;
        }

        int end = poststart;
        for(end; end < postend; end++){
            if(post[end] == pre[prestart+1]){
                break;
            }
        }

        root->left = constructBinaryTree(pre, post, prestart+1, prestart+end-poststart+1, poststart, end);
        root->right = constructBinaryTree(pre, post, prestart+end-poststart+2, preend, end+1, postend-1);
        
        return root;
    }
};